package com.emm.yixun.website.controller.estate;

import com.emm.yixun.common.excel.FastExcel;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.MathUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.PriceSchemeServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.task.utils.ExcelReader;
import com.emm.yixun.website.vo.CustomerImportVo;
import com.emm.yixun.website.vo.common.ExtResultVo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 类描述： EXCEL处理类
* 创建者： ThinkPad
* 项目名称： emm-website
* 创建时间： 2016年8月8日 上午10:58:21
* 版本号： v1.0
 */
@RequestMapping(value = "/estate/excel")
@Controller
public class EstateExcelController extends BaseController<Object>{

	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	/**
	* 方法描述 : 动态生成EXCEL
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ExcelController.java
	* 版本： v1.0
	* 创建时间： 2016年8月8日 上午11:21:10
	* @param request
	* @param treeId
	* @param response void
	 */

	@RequestMapping(value = "downloadRoomsInfo")
	public void downloadExcelModel(HttpServletRequest request, HttpServletResponse response, String treeId){
		try {
		  	@SuppressWarnings("resource")
		  	HSSFWorkbook wb = new HSSFWorkbook();
		  	HSSFSheet sheet = wb.createSheet("公安编号");
		  	HSSFCellStyle headStyle = wb.createCellStyle();
		  	HSSFFont f  = wb.createFont();
		  	f.setFontHeightInPoints((short) 11);// 字号
		  	f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		  	headStyle.setFont(f);
		  	headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		  	headStyle.setBorderBottom((short) 1);
		  	headStyle.setBorderRight((short) 1);
		  	headStyle.setFillBackgroundColor((short) 20);
		  	HSSFRow row = sheet.createRow((int) 0);
		  	//创建单元格，并设置值表头 设置表头居中
		  	HSSFCellStyle style = wb.createCellStyle();
		  	style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		  	style.setBorderBottom((short) 1);
		  	style.setBorderRight((short) 1);
		  	String changeField = null;
		  	String[] header = new String[]{"房源编号","房号","项目名称","组团名称","楼栋名称","单元名称","房间名称"};
			for (int i = 0; i < header.length; i++)  {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(style);
				HSSFRichTextString text = new HSSFRichTextString(header[i]);
				cell.setCellValue(text);
			}
			HSSFCell cell = null;
			if(StringUtils.isNotEmpty(treeId)){
				String objectType = treeId.substring(0, treeId.indexOf("_"));
				String objectId = treeId.substring(treeId.indexOf("_") + 1);
				ProjectRoomDto projectRoomDto = new ProjectRoomDto();
				if(objectType.equals("PROJECT")){
					projectRoomDto.setProjectId(Long.valueOf(objectId));
				}else if(objectType.equals("PREMISES")){
					projectRoomDto.setPremisesId(Long.valueOf(objectId));
				}else if(objectType.equals("BUILDING")){
					projectRoomDto.setBuildingId(Long.valueOf(objectId));
				}else if(objectType.equals("UNIT")){
					projectRoomDto.setUnitId(Long.valueOf(objectId));
				}else if(objectType.equals("ROOM")){
					projectRoomDto.setRoomId(Long.valueOf(objectId));
				}
				projectRoomDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<ProjectRoom> result = projectRoomServiceFacade.findByDto(projectRoomDto).getEntity();
				int rowId = 1;
				for (int j = 0; j < result.size(); j++) {
					ProjectRoom projectRoom = result.get(j);
					row = sheet.createRow(rowId);
					cell = row.createCell(0,1);
					cell.setCellValue(projectRoom.getId());
					cell = row.createCell(1,1);
					cell.setCellValue(projectRoom.getCombinedName());
					cell = row.createCell(2,1);
					cell.setCellValue("");
					cell = row.createCell(3,1);
					cell.setCellValue("");
					cell = row.createCell(4,1);
					cell.setCellValue("");
					cell = row.createCell(5,1);
					cell.setCellValue("");
					cell = row.createCell(6,1);
					cell.setCellValue("");
					rowId++;
				}
			}

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		  	String mimetype = "application/x-msdownload";
		  	String downFileName = "excel-"+df.format(new Date())+".xls";
		  	String inlineType = "attachment";
		  	response.setHeader("Content-Disposition", inlineType  + ";filename=\"" + downFileName + "\"");
			OutputStream out=response.getOutputStream();
		  	response.setContentType(mimetype);
		  	wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Workbook create(InputStream in) throws IOException,InvalidFormatException {
		if (!in.markSupported()) {
			in = new PushbackInputStream(in, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(in)) {
			return new HSSFWorkbook(in);
		}
		if (POIXMLDocument.hasOOXMLHeader(in)) {
			return new XSSFWorkbook(OPCPackage.open(in));
		}
		throw new IllegalArgumentException("你的excel版本目前poi解析不了");
	}

	/**
	* 方法描述 : 导入模版数据
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： ExcelController.java
	* 版本： v1.0
	* 创建时间： 2016年8月8日 下午3:06:26
	* @param request
	* @param response
	* @param multipartFile
	* @return AjaxRes
	 */
	@RequestMapping(value = "importModel")
	public @ResponseBody AjaxRes importModel(HttpServletRequest request, HttpServletResponse response, @RequestParam("multipartFile")MultipartFile multipartFile, String treeId){
		AjaxRes ar = getAjaxRes();
		try {
			//解析Excel数据并转为java实体bean
			FastExcel fastExcel=new FastExcel(multipartFile.getInputStream());
			fastExcel.setStartRow(1);
			fastExcel.setSheetName("公安编号");
			List<ProjectRoomCodeModel> projectRoomList = fastExcel.parse(ProjectRoomCodeModel.class);
			fastExcel.close();

			int totalCount = 0;
			int successCount = 0;
			int failureCount = 0;
			if(null != projectRoomList && projectRoomList.size() > 0){
				totalCount = projectRoomList.size();
				String objectType = treeId.substring(0, treeId.indexOf("_"));
				String objectId = treeId.substring(treeId.indexOf("_") + 1);
				for(ProjectRoomCodeModel roomModel: projectRoomList){
					try {
						/*
						boolean flag = true;
						Response<ProjectRoom> roomRes = projectRoomServiceFacade.findById(Long.valueOf(roomModel.getRoomId()));
						if(roomRes.isSuccess() && null != roomRes.getEntity()){
							ProjectRoom room = roomRes.getEntity();
							if(objectType.equals("PROJECT")){
								if(room.getProjectId().compareTo(Long.valueOf(objectId)) != 0){
									flag = false;
								}
							}else if(objectType.equals("PREMISES")){
								if(room.getPremisesId().compareTo(Long.valueOf(objectId)) != 0){
									flag = false;
								}
							}else if(objectType.equals("BUILDING")){
								if(room.getBuildingId().compareTo(Long.valueOf(objectId)) != 0){
									flag = false;
								}
							}else if(objectType.equals("UNIT")){
								if(room.getUnitId().compareTo(Long.valueOf(objectId)) != 0){
									flag = false;
								}
							}else if(objectType.equals("ROOM")){
								if(room.getId().compareTo(Long.valueOf(objectId)) != 0){
									flag = false;
								}
							}
						}
						*/
						ProjectRoomDto projectRoomDto = new ProjectRoomDto();
						if(StringUtils.isEmpty(roomModel.getRoomId())){
							failureCount++;
							continue;
						}

						projectRoomDto.setId(Long.valueOf(roomModel.getRoomId()));
						projectRoomDto.setProjectSecName(roomModel.getProjectSecName());
						projectRoomDto.setPremisesSecName(roomModel.getPremisesSecName());
						projectRoomDto.setBuildingSecName(roomModel.getBuildingSecName());
						projectRoomDto.setUnitSecName(roomModel.getUnitSecName());
						projectRoomDto.setRoomSecName(roomModel.getRoomSecName());
						Response<Integer> res = projectRoomServiceFacade.updateByDto(projectRoomDto);
						if(res.isSuccess()){
							if(res.getEntity() > 0){
								successCount++;
							}else{
								failureCount++;
							}
						}
					}catch (Exception ex){
						failureCount++;
						logger.error("导入失败,房源Id: {}", roomModel.getRoomId());
					}
				}
			}
			String result = "共导入" + totalCount + "笔房源, 有效" + successCount + "笔,失败" + failureCount + "笔。";
			ar.setSucceed(result);
		} catch (Exception ex) {
			logger.error("导入公安编号错误", ex);
			ex.printStackTrace();
			String result = "数据错误,请重新下载数据并导入!";
			ar.setFailMsg(result);
		}
		return ar;
	}
}
